<?php
namespace Home\Controller;
use Think\Controller;
use Think\Upload;

class GoodsController extends Controller {
	
	public function __construct(){  //钩子函数
		parent::__construct();
		
		if(empty($_SESSION['user']))
		{
			 $this->error('对不起,您还没有登录!请先登录!', U('Login/login'), 1);
			
		}
	}

	//展示产品列表
	public function lst(){
		$goods=M('products');  //产品表

		if(IS_POST){
			$data = I('post.');

			//dump($data);die;
			
		}else{

			$join='left join category c on c.id=p.cateid';
			$res = $goods->field('p.*,c.catename')->alias('p')->join($join)->order('id desc')->select();
			//dump($res);die;
			
		}

		$this->assign('res',$res);
		$this->display();
	}

	public function catemanage(){

		$cate=M('category');
		if(IS_POST && !empty(I('post.makesort'))){  //判断是否来自排序的提交
			$data = I('post.');
			unset($data['makesort']);  //去掉submit 的键值
			$tmp=array();
			foreach($data['id'] as $k=>$v){
				$tmp[$k]['id'] = $v;
			}
			

			foreach ($data['sort'] as $k => $v) {
				$tmp[$k]['sort'] = $v;
			}
			//dump($tmp);die;
			$i=0;
			foreach($tmp as $k=>$v){  //循环存储排序
				$saveSort = $cate->save($v);
				if($saveSort===false){
					$i+=1;
				}
				if($i>0){
					$this->error('排序保存失败!');
				}
			}
			$this->success('排序设置成功！',U('catemanage'),'',1);  //1秒显示

		}
		
		$cateres = $cate->order('sort asc')->select();  //按升序拍， 号小在前面
		$this->assign('cateres',$cateres);
		
		$this->display();
	}


	//编辑类目
	public function edit_cate(){
		$cate=M('category');
		
		if(IS_POST){
			$data = I('post.');
			foreach($data as &$v){   //去掉输入时候的空格
				$v['catename'] = trim($v['catename']);
				$v['encatename'] = trim($v['encatename']);
				$v['sort'] = trim($v['sort']);
			}
			$saveRes = $cate->save($data);
			if($saveRes!==false){
				$this->success('更新成功！',U('catemanage'));
			}
		}

		$id = I('get.id');
		
		$cateres = $cate->find($id);  //查找ID对应的类信息
		$this->assign([
			'cateres'=>$cateres,
			
		]);
		
		$this->display();
	}


	

	//添加产品信息
	public function add(){
		$goods=M('products');

		if(IS_POST){
			//dump(I('post.')); die;
			//dump($_FILES);die;
			$data = I('post.','','htmlspecialchars');
			//empty($data['cateid']) && $this->error('请选择商品的所属类目');  //判断商品类目是否为空 商品cateid 不能为0； 但是类目的PID 可以为0.   0对于类目，就是顶级目录的标识
			

			//先判断 有无图片文件上传
			if(isset($_FILES['product_img']['tmp_name']) && !empty($_FILES['product_img']['tmp_name'])){

				$upload = new \Think\Upload();
				$upload->maxSize   =     500000 ;// 设置附件上传大小  <= 500k
			    $upload->exts      =     array('jpg', 'jpeg','bmp','png');// 设置附件上传类型
			    $upload->rootPath  =     ROOT_PATH.'/Public/product_img/'; // 设置附件上传根目录
			    $upload->savePath  =     ''; // 设置附件上传（子）目录
			    $upload->subName   =     array('date','Ymd');
			    $info   =   $upload->upload();
			    
			    /*if(!$info) {// 上传错误提示错误信息
	       		 	$this->error();

	   	    	}*/

	   	    	$data['product_img'] = '/'.$info['product_img']['savepath'].$info['product_img']['savename'];
	   	    	//dump($data);die;
	   	    	//上传成功则 录入其它信息
   	    	}
   	    		
   	   
   	   	   	$res = $goods->add($data);
   	   		
   	    	
   	    	if($res){
   	    		$this->success('添加成功',U('lst'),1);
   	    	}else{
   	    		$this->error('添加失败','',2);
   	    	}


		
		}

		//获取类目下拉菜单
		$cat = M('category')->select();
		$cat = $this->sort($cat);
		//dump($cat);die;
		$this->assign('cat',$cat);
		$this->display();

	}


	//添加 类目信息
	public function add_cate(){
		$cat = M('category');

		//顶级类目
		if(I('post.add_top')){
			$data = I('post.');
			unset($data['add_top']);  //删除表单按钮的值
			$res = $cat->add($data);
			if($res){
				$this->success('添加顶级类目成功',U('add_cate'),1);
			}else{
   	    		$this->error('连接服务失败','',2);
   	    	}
		}

		//子类目
		if(I('post.add_sub')){

			$data = I('post.');
			//dump($data);die;
			unset($data['add_sub']);  //删除表单按钮的值
			$res = $cat->add($data);
			if($res){
				$this->success('添加子类目成功',U('add_cate'),1);
			}else{
   	    		$this->error('连接服务失败','',2);
   	    	}
		}



		$res = $cat->select();
		$res = $this->sort($res);
		$this->assign('res',$res);
		$this->display();
	}

	//编辑商品信息
	public function goods_edit(){
		
		$goods = M('products');	
		$id = I('get.id');

		
		$goodsInfo = $goods->find($id);
		$goodsInfo['details'] = html_entity_decode($goodsInfo['details']);  //html_entity_decode 该函数将 html 转化， 就不会显示html 代码details
		$goodsInfo['endetails'] = html_entity_decode($goodsInfo['endetails']);
		$goodsInfo['product_img'] = '/Public/product_img'.	$goodsInfo['product_img'];

		//
		if(IS_POST){
			$data =  I('post.','','htmlspecialchars');
			empty($data['cateid'])  && $this->error('商品类目不能为空！');

			//先判断 有无图片文件上传
			if(isset($_FILES['product_img']['tmp_name']) && !empty($_FILES['product_img']['tmp_name'])){

				$upload = new \Think\Upload();
				$upload->maxSize   =     500000 ;// 设置附件上传大小  <= 500k
			    $upload->exts      =     array('jpg', 'jpeg','bmp','png');// 设置附件上传类型
			    $upload->rootPath  =     ROOT_PATH.'/Public/product_img/'; // 设置附件上传根目录
			    $upload->savePath  =     ''; // 设置附件上传（子）目录
			    $upload->subName   =     array('date','Ymd');
			    $info   =   $upload->upload();
			    
			    /*if(!$info) {// 上传错误提示错误信息
	       		 	$this->error();

	   	    	}*/

	   	    	$data['product_img'] = '/'.$info['product_img']['savepath'].$info['product_img']['savename'];
	   	    	//dump($data);die;
	   	    	//上传成功则 录入其它信息
   	    	}

    		$res = $goods->save($data);
   	   		
   	    	
   	    	if($res!==false){
   	    		$this->success('修改成功',U('lst'),1);
   	    	}else{
   	    		$this->error('修改失败','',1);
   	    	}



		}

		//获取类目下拉菜单
		$cat = M('category')->select();
		$cat = $this->sort($cat);
		// dump($goodsInfo);die;

		$this->assign([
			'goodsInfo'=>$goodsInfo,
			'cat' => $cat,
		]);
		$this->display();

	}

	//计算子目录层级
	public function sort($cateRes,$pid=0,$level=0){

        static $arr=array();
        foreach ($cateRes as $k => $v) {
            if($v['pid'] == $pid){
                $v['level']=$level;
                $arr[]=$v;
                $this->sort($cateRes,$v['id'],$level+1);
            }
        }
        return $arr;
    }

    //删除商品信息
	public function goods_del($id){
		//删除之前， 先删除对应的图片
		$goods = M('products');
		$picPath = $goods->field('id,product_img')->find($id);
		$fullPath = ROOT_PATH . '/Public/product_img'. $picPath['product_img'];
		//echo $fullPath;die;
		if(is_file($fullPath)){
			@unlink($fullPath);   //删除图片
		}
		

		$goods->delete($id);
		$this->success('删除成功',U('lst'),1);
	}

}